<?php

namespace addons\wechat\controller;

use addons\wechat\library\Config;
use addons\wechat\model\WechatAutoreply;
use addons\wechat\model\WechatCaptcha;
use addons\wechat\model\WechatContext;
use addons\wechat\model\WechatResponse;
use addons\wechat\model\WechatConfig;

use EasyWeChat\Factory;
use addons\wechat\library\Wechat as WechatService;
use addons\wechat\library\Config as ConfigService;
use fq\request\LoadRequest;
use think\Log;

/**
 * 微信接口
 */
class Index extends \think\addons\Controller
{

    public $app = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->app = Factory::officialAccount(Config::load());
    }

    /**
     *
     */
    public function index()
    {

        $this->error("当前插件暂无前台页面");
    }

    /**
     * 微信API对接接口
     */
    public function api()
    {
        $this->app->server->push(function ($message) {
            $wechatService = new WechatService;
            trace('++++++++++++++++++++++++');
            trace($message);
            $matches = null;
            $openid = $message['FromUserName'];
            $to_openid = $message['ToUserName'];

            $unknownMessage = WechatConfig::getValue('default.unknown.message');
            $unknownMessage = $unknownMessage ? $unknownMessage : "";

            switch ($message['MsgType']) {
                case 'event': //事件消息
                    $event = $message['Event'];
                    $eventkey = $message['EventKey'] ?? $message['Event'];
                    //验证码消息
                    if (in_array($event, ['subscribe', 'SCAN']) && preg_match("/^captcha_([a-zA-Z0-9]+)_([0-9\.]+)/", $eventkey, $matches)) {
                        return WechatCaptcha::send($openid, $matches[1], $matches[2]);
                    }
                    switch ($event) {
                        case 'subscribe'://添加关注
                            $subscribeMessage = WechatConfig::getValue('default.subscribe.message');
                            $subscribeMessage = $subscribeMessage ? $subscribeMessage : "欢迎关注我们!";
                            return $subscribeMessage;
                        case 'unsubscribe'://取消关注
                            return '';
                        case 'LOCATION'://获取地理位置
                            return '';
                        case 'VIEW': //跳转链接,eventkey为链接
                            return '';
                        case 'SCAN': //扫码
                            return '';
                        default:
                            break;
                    }

                    $wechatResponse = WechatResponse::where(["eventkey" => $eventkey, 'status' => 'normal'])->find();
                    if ($wechatResponse) {
                        $responseContent = (array)json_decode($wechatResponse['content'], true);
                        $wechatContext = WechatContext::where(['openid' => $openid])->order('id', 'desc')->find();
                        $data = ['eventkey' => $eventkey, 'command' => '', 'refreshtime' => time(), 'openid' => $openid];
                        if ($wechatContext) {
                            $wechatContext->save($data);
                        } else {
                            $wechatContext = WechatContext::create($data, true);
                        }
                        $result = $wechatService->response($this, $openid, '', $responseContent, $wechatContext);
                        if ($result) {
                            return $result;
                        }
                    }
                    return $unknownMessage;
                case 'text': //文字消息
                    trace($message['Content'], 'error');
                    db('wechatMessage')->insert(array_merge($message));
                    db('wechatTmplmsg')->insert(['title' => $openid, 'content' => $message['Content']]);
                    $tmplId = db('wechatTmplmsg')->getLastInsID();
                    //cache
                    if (strpos($message['Content'], '**') !== false) {
                        $cache = substr($message['Content'], 2);
                        cache('tpwd', $cache, 7200);
                        return $cache;
                    }

                    if (isMobile($message['Content']) !== false) {

                        return file_get_contents('https://card.tbpdd.top/api/kbs/profit?mobile=' . $message['Content']);
                    }


                    //抖音视频真实地址
                    if (strpos($message['Content'], 'v.douyin.com') !== false) {
                        $dd = ['url' => $message['Content']];
                        $video = file_post_contents('https://yuanxiapi.cn/api/jiexi_video/', $dd);

                        $videos = @json_decode($video, true);
                        if (isset($videos['video'])) {
                            trace($videos['video']);
                            return $videos['video'];
                        }

                    }

                    //京东商品转链
                    if (strpos($message['Content'], 'https://3.cn') !== false) {

                        $jdDetail = jd_detail($message['Content']);
                        if($jdDetail) return $jdDetail;

                        return '找不到京东商品';
                    }

                    if (strpos($message['Content'], 'jd.com') !== false) {
                        $_content = jd_url($message['Content']);
                        if ($_content) return $_content;
                    }


                    //实时线报查询
                    if (substr($message['Content'], 0, 2) == ',,') {
                        $search = substr($message['Content'], 2);
                        $result = db('wireReport')
                            ->where('source', 1)
                            ->where('content', 'like', "%$search%")
                            ->select();
                        return json_encode($result, 256);
                    }
                    trace($message['Content'], 'error');
                    // 使用免费的好单库工具
                    $item = hdk_taoword($message['Content']);
                    if (isset($item['data']['taoword'])) {
                        $tpwd = '//:'.$item['data']['taoword'];
                        $title = $item['data']['itemtitle'];
                        $itemid = $item['data']['itemid'];
                        $itemprice = $item['data']['itemprice'];
                        $itemendprice = $item['data']['itemendprice'];
                        $rates = $item['data']['tkrates'];

                    } else {
                        $item = hdk_parse($message['Content']);
                        if (!isset($item['data']['item_id'])) {
                            return '未发现商品链接';
                        }
                        $tpwd = $item['data']['trans_tpwd']['password_simple'];
                        $title = $item['data']['item_title'];
                        $itemid = $item['data']['item_id'];
                        $itemprice = $item['data']['item_price'];
                        $itemendprice = $item['data']['item_end_price'];
                        $rates = $item['data']['rates'];
                    }

                    //计算利润
                    $lj = 0.8;
                    $profit = round($itemendprice * $rates * $lj / 100, 2);
                    $tljword = '';
                    if ($profit > 20) $profit = 20;
                    if ($profit >= 1) {
                        $tlj = get_tlj($itemid, $profit, $itemendprice);
                        trace($tlj,'info');
                        if (isset($tlj['tpwd'])) {
                            $tpwd = $tlj['tpwd'];
                            $tljword = "★【补贴】{$profit}";
                        }
                    }
                    $content = "{$title}                  
★【原价】{$itemprice}
★【券后】{$itemendprice}
$tljword
︾︾︾︾︾︾
长按复制下面内容，打开淘宝即可享受优惠
{$tpwd}";

                    db('wechatMessage')->where('MsgId', $message['MsgId'])
                        ->setField('Response', $content);


                    return $content;


                    break;
                case 'image': //图片消息
                case 'voice': //语音消息
                case 'video': //视频消息
                case 'location': //坐标消息
                case 'link': //链接消息
                default: //其它消息
                    //自动回复处理
                    if ($message['MsgType'] == 'text') {
                        $autoreply = null;
                        $autoreplyList = WechatAutoreply::where('status', 'normal')->cache(true)->order('weigh DESC,id DESC')->select();
                        foreach ($autoreplyList as $index => $item) {
                            //完全匹配和正则匹配
                            if ($item['text'] == $message['Content'] || (in_array(mb_substr($item['text'], 0, 1), ['#', '~', '/']) && preg_match($item['text'], $message['Content'], $matches))) {
                                $autoreply = $item;
                                break;
                            }
                        }

                        if ($autoreply) {
                            $wechatResponse = WechatResponse::where(["eventkey" => $autoreply['eventkey'], 'status' => 'normal'])->find();
                            if ($wechatResponse) {
                                $responseContent = (array)json_decode($wechatResponse['content'], true);
                                $wechatContext = WechatContext::where(['openid' => $openid])->order('id', 'desc')->find();
                                $result = $wechatService->response($this, $openid, $message['Content'], $responseContent, $wechatContext, $matches);
                                if ($result) {
                                    return $result;
                                }
                            }
                        }
                    }
                    return $unknownMessage;
            }
            return ""; //SUCCESS
        });

        $response = $this->app->server->serve();
        // 将响应输出
        $response->send();
        return;
    }

    /**
     * 登录回调
     */
    public function callback()
    {

    }

    /**
     * 支付回调
     */
    public function notify()
    {
        Log::record(file_get_contents('php://input'), "notify");
        $response = $this->app->handlePaidNotify(function ($message, $fail) {
            // 你的逻辑
            return true;
            // 或者错误消息
            $fail('Order not exists.');
        });

        $response->send();
        return;
    }

    /**
     * 发送模板消息
     */
    public function tmplmsg()
    {
        $openid = config('openid');
        if (input('id')) {
            $msg = db('wechatTmplmsg')->where('id', input('id'))->find();
            if (isset($openid[$msg['title']])) {
                $msg['title'] = $openid[$msg['title']];
            }

            echo "<html>
 <head>
  <title>{$msg['title']}</title>
 </head>
 <body style='padding: 21px;font-size: 36px'>
 {$msg['content']}
 <br>--------------------------<br>
 {$msg['response']}
 </body>
</html>";
        } else {
            $msgs = db('wechatTmplmsg')->where('msgid', 0)->select();
            foreach ($msgs as $msg) {
                $res = $this->app->template_message->send([
                    'touser' => 'o2Y9V1XrAJtMzT-Y6YwZGvyk3MvA',
                    'template_id' => 'YqpIvja84-uTraxRnEwrzr_atepmxaqsf-a1L8g9t6Q',
//                    'url' => $msg['url'],
                    'data' => [
                        'msg' => $msg['content'],
                    ],
                ]);
                if (isset($res['msgid'])) {
                    db('wechatTmplmsg')->where('id', $msg['id'])->setField('msgid', $res['msgid']);
                }
                dump($res);
            }
        }

    }

}
